using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using System.IO;
/*
	ToDo: review which of these are still used!
*/
namespace DbView
{
	/// <summary>
	/// Summary description for Helper.
	/// </summary>
	public class Helper
	{
		public Helper() { }

		// this one mainly for Xml
		public static String FormatLongCellDataForDisplay(String data)
		{
			if (data.IndexOf("<") != -1 && data.IndexOf(">") != -1) // might be Xml
			{
				try
				{
					XmlDocument doc = new XmlDocument();
					doc.LoadXml(data);
					data = FormatXML(doc);
				}
				catch (SystemException exc)
				{
					String message = exc.Message;
				}
			}
			return data;
		}

		// new 2011 Xml Helper
		public static String FormatXML(XmlDocument doc)
		{
			// Create a stream buffer that can be read as a string
			using (StringWriter sw = new StringWriter())

			// Create a specialized writer for XML code
			using (XmlTextWriter xtw = new XmlTextWriter(sw))
			{
				// Set the writer to use indented (hierarchical) elements
				xtw.Formatting = System.Xml.Formatting.Indented;

				// Write the XML document to the stream
				doc.WriteTo(xtw);

				// Return the stream as a string
				return sw.ToString();
			}
		}

		public static int getSelectedRow(DataGridView results, out DataRow selectedRow)
		{
			// DataGridViewRow relates to DataGridView
			DataGridViewRow current = results.CurrentRow;
			// Detect right-click in the edit buffer.
			selectedRow = null;
			if (current == null) return -1;
			if (current.DataBoundItem == null) return -1;

			// this is related to a view of the data via the DataBoundItem prop.
			DataRowView rv = (DataRowView)current.DataBoundItem;
			selectedRow = rv.Row;
			BindingSource bSource = (BindingSource)results.DataSource;
			DataTable dt = (DataTable)bSource.DataSource;
			for (int idx2 = 0; idx2 < dt.Rows.Count; ++idx2)
				if (dt.Rows[idx2] == selectedRow)
					return idx2;
			return 0;
		}

		//public static String makeSearchClause(String seek)
		//{
		//    String clause = String.Format("like \'%{0}%\'", seek.Trim());
		//    if (seek.Length == 0)
		//        return clause;
		//    // get beginning and end chars
		//    char first = seek[0];
		//    char last = seek[seek.Length - 1];
		//    // use regex 
		//    if (first == '^' && last == '$')
		//        return String.Format("= '{0}'", seek.Substring(1, seek.Length - 2));
		//    // assume it will be "like '%xxx%'
		//    if (first == '^')
		//        return String.Format("like \'{0}%\'", seek.Substring(1, seek.Length - 1).Trim());
		//    else
		//        // assume it will be "like '%xxx%'
		//        if (last == '$')
		//            return String.Format("like \'%{0}\'", seek.Substring(0, seek.Length - 1));
		//    return clause;

		//}

		//public static String safeSqlField(String field)
		//{
		//    if (field.Length == 0)
		//        return field;
		//    if (field[0] == '[' && field[field.Length - 1] == ']')
		//        return field;
		//    // hacked fix for aliased fields.
		//    if (field.IndexOf('.') > 0)
		//        return field;
		//    return "[" + field.Trim() + "]"; // does not allow for fields with leading & trailing spaces
		//}

		//public static void GenericMakeDset(String strConnectionString, String sql, String strTableName, out DataSet dset)
		//{
		//    // Create a data reading object to fill the dataset
		//    dset = new DataSet();
		//    SqlConnection sqlConn = new SqlConnection();
		//    try
		//    {
		//        // get the connection 
		//        sqlConn.ConnectionString = strConnectionString;
		//        sqlConn.Open();

		//        SqlDataAdapter da = new SqlDataAdapter(sql, sqlConn);
		//        // execute into something
		//        da.Fill(dset, strTableName);
		//        sqlConn.Close();
		//    }
		//    catch (SqlException e)
		//    {
		//        /*        This is old-style
		//                        // fake the message into a table
		//                        DataTable dt = new DataTable("Error");
		//                        dset.Tables.Add(dt);
		//                        DataColumn ErrCol = dt.Columns.Add("Error", typeof(String));
		//                        object [] DataArray = new object[1];
		//                        DataRow dr = dt.NewRow();
		//                        dt.Rows.Add(dr);
		//                        DataArray[0] = e.Message;
		//                        dr.ItemArray = DataArray;
		//                        // may not work if connection fails
		//                        sqlConn.Close();
		//        */

		//        // may not work if connection fails
		//        sqlConn.Close();
		//        String Message = String.Format("Sql Error: {0}\n" +
		//                                       "connection: {1}\n" +
		//                                        "Sql: {2}\n",
		//                                        e.Message, strConnectionString, sql);
		//        Exception ex = new Exception(Message);
		//        throw ex; // abort process having logged as much as possible.
		//    }
		//}
		//public static String GenericExecute(String strConnectionString, String Sql)
		//{
		//    String returnMessage = "";
		//    // establish a SQL connection
		//    SqlConnection sqlConn = new SqlConnection();
		//    sqlConn.ConnectionString = strConnectionString;
		//    SqlCommand Command = new SqlCommand(Sql, sqlConn);
		//    try
		//    {
		//        Command.Connection.Open();
		//        int rows = Command.ExecuteNonQuery();
		//        returnMessage = "Command completed";
		//        if (rows != -1)
		//            returnMessage += String.Format("\n{0} rows affected", rows);
		//    }
		//    catch (System.Data.SqlClient.SqlException e)
		//    {
		//        returnMessage = e.Message;
		//    }
		//    finally
		//    {
		//        Command.Connection.Close();
		//    }
		//    return returnMessage;
		//}
		//public static bool TestConnection(String strConnectionString, out String message)
		//{
		//    message = ""; // OK 
		//    bool bTestedOk = true;
		//    // Create a data reading object to fill the dataset
		//    DataSet dset = new DataSet();
		//    SqlConnection sqlConn = new SqlConnection();
		//    try
		//    {
		//        // get the connection 
		//        sqlConn.ConnectionString = strConnectionString;
		//        sqlConn.Open();

		//        SqlDataAdapter da = new SqlDataAdapter("SELECT @@VERSION", sqlConn);
		//        // execute into something
		//        da.Fill(dset, "VERSION");
		//        sqlConn.Close();
		//        message = "OK:\n" + dset.Tables[0].Rows[0][0].ToString();
		//    }
		//    catch (SqlException e)
		//    {
		//        message = String.Format("{0}", e.Message);
		//        // may not work if connection fails
		//        sqlConn.Close();
		//        bTestedOk = false;
		//    }
		//    return bTestedOk;
		//}

		//public static String DocFromDset(String strConnectionString, String sql, int sourceCol, bool AddNewLine)
		//{
		//    SqlConnection sqlConn = new SqlConnection();
		//    // get the connection 
		//    sqlConn.ConnectionString = strConnectionString;
		//    sqlConn.Open();
		//    // get the string part
		//    // build the query
		//    // Create a data reading object to fill the dataset
		//    SqlDataAdapter da = new SqlDataAdapter(sql, sqlConn);
		//    DataSet sourceLines = new DataSet();
		//    // execute into something
		//    da.Fill(sourceLines);

		//    // use stringbuilder?
		//    String sourceCode = "";
		//    foreach (DataRow r in sourceLines.Tables[0].Rows)
		//    {
		//        sourceCode += r[sourceCol].ToString();
		//        if (AddNewLine)
		//            sourceCode += "\n";
		//    }
		//    return sourceCode;
		//}

		// Naughty. This is in the drivers now.
		//public static String GetSourceCode(String strConnectionString, String strSelectedObject)
		//{
		//    String sql = String.Format(@"SELECT so.name, sc.text" +
		//        " FROM sysobjects so" +
		//        " INNER JOIN syscomments sc ON so.id = sc.id" +
		//        " WHERE so.name ='{0}' ORDER BY sc.colid", strSelectedObject);
		//    return DocFromDset(strConnectionString, sql, 1, false);
		//}

		//public static void GetStructure(String strConnectionString, String strSelectedObject, out DataSet dset)
		//{
		//    // if a view or table
		//    // build the query
		//    String strTmpl = "select top 0 * from [{0}]";
		//    String sql = String.Format(strTmpl, strSelectedObject);
		//    SqlConnection sqlConn = new SqlConnection();
		//    // get the connection 
		//    sqlConn.ConnectionString = strConnectionString;
		//    SqlCommand theCommand = new SqlCommand(sql, sqlConn);
		//    sqlConn.Open();
		//    SqlDataReader theReader;
		//    // Create a SQl reader
		//    dset = new DataSet();
		//    try
		//    {
		//        theReader = theCommand.ExecuteReader();
		//        // Create a data reading object to fill the dataset

		//        // have to add columns
		//        DataTable Src = theReader.GetSchemaTable();
		//        // remove some 
		//        Src.Columns.Remove("ColumnOrdinal");
		//        Src.Columns.Remove("NumericPrecision");
		//        Src.Columns.Remove("NumericScale");
		//        Src.Columns.Remove("IsUnique");
		//        Src.Columns.Remove("IsKey");
		//        Src.Columns.Remove("BaseCatalogName");
		//        Src.Columns.Remove("BaseColumnName");
		//        Src.Columns.Remove("BaseSchemaName");
		//        Src.Columns.Remove("BaseServerName");
		//        Src.Columns.Remove("BaseTableName");

		//        dset.Tables.Add(Src);
		//        sqlConn.Close();
		//    }
		//    catch (SqlException e)
		//    {
		//        // fake the message into a table
		//        DataTable dt = new DataTable("Error");
		//        dset.Tables.Add(dt);
		//        DataColumn ErrCol = dt.Columns.Add("Error", typeof(String));
		//        object[] DataArray = new object[1];
		//        DataRow dr = dt.NewRow();
		//        dt.Rows.Add(dr);
		//        DataArray[0] = e.Message;
		//        dr.ItemArray = DataArray;
		//        // may not work if connection fails
		//        sqlConn.Close();
		//    }
		//}

		//public static void GetExtraTableStructureInfo(String strConnectionString, String strTableName, out DataSet dset)
		//{
		//    // dig into extra info
		//    String strTmpl = "exec sp_help {0}";
		//    String sql = String.Format(strTmpl, strTableName);
		//    SqlConnection sqlConn = new SqlConnection();
		//    // get the connection 
		//    sqlConn.ConnectionString = strConnectionString;
		//    dset = new DataSet();
		//    try
		//    {
		//        sqlConn.Open();

		//        SqlDataAdapter da = new SqlDataAdapter(sql, sqlConn);
		//        // execute into something
		//        da.Fill(dset, strTableName);
		//        sqlConn.Close();
		//    }
		//    catch (SqlException e)
		//    {
		//        // fake the message into a table
		//        DataTable dt = new DataTable("Error");
		//        dset.Tables.Add(dt);
		//        DataColumn ErrCol = dt.Columns.Add("Error", typeof(String));
		//        object[] DataArray = new object[1];
		//        DataRow dr = dt.NewRow();
		//        dt.Rows.Add(dr);
		//        DataArray[0] = e.Message;
		//        dr.ItemArray = DataArray;
		//        // may not work if connection fails
		//        sqlConn.Close();
		//    }
		//}

		// drag drop helpers	
		// 
		//public static void OnDDUpdateList(ListBox listBox, System.Windows.Forms.DragEventArgs e)
		//{
		//    // test for presence of string data
		//    if (e.Data.GetDataPresent(DataFormats.StringFormat))
		//    {
		//        // item from source
		//        string item = (string)e.Data.GetData(DataFormats.StringFormat);
		//        // convert from screen to listbox co-ordinates
		//        Point p = listBox.PointToClient(new Point(e.X, e.Y));
		//        // find list position for insertion from mouse position
		//        int insertAt = listBox.IndexFromPoint(p);
		//        bool appending = (insertAt == -1);  // item will be appended
		//        if (appending)
		//            insertAt = listBox.Items.Count; // this adjustment makes the logic below easier
		//        // find current position of item in list (-1 if not present)
		//        int currentPos = listBox.Items.IndexOf(item);
		//        bool newItem = (currentPos == -1);
		//        // set flag if item is moving down the list
		//        bool movingDown = (!newItem && (insertAt > currentPos));
		//        // apply logic
		//        // if no change 
		//        if (insertAt == currentPos)
		//        {
		//            // no action dropping in old position
		//            currentPos += 0; // this is a no-change statement to purge a compiler warning
		//        }
		//        else
		//        {
		//            // test for item moving down
		//            if (movingDown)
		//            {
		//                // increase insertion point to account for removing the original
		//                ++insertAt;
		//                // test edge case where moving to the end
		//                if (insertAt >= listBox.Items.Count)
		//                    appending = true;
		//            }
		//            // add the item
		//            if (appending)
		//                listBox.Items.Add(item);
		//            else
		//                listBox.Items.Insert(insertAt, item);
		//            // set the index to the dropped item
		//            // listBox.SelectedIndex = insertAt;
		//            // find item to remove
		//            if (!newItem)
		//                if (movingDown)
		//                    listBox.Items.RemoveAt(currentPos);
		//                else
		//                    listBox.Items.RemoveAt(currentPos + 1);

		//            listBox.SelectedIndex = listBox.Items.IndexOf(item);
		//        }
		//    }
		//}
		//public static void OnDDRemoveFromList(ListBox listBox, String s)
		//{
		//    int removeAt = listBox.Items.IndexOf(s);
		//    if (removeAt != -1)
		//    {
		//        listBox.Items.RemoveAt(removeAt);
		//        removeAt -= (removeAt >= listBox.Items.Count) ? 1 : 0;
		//        listBox.SelectedIndex = removeAt;
		//    }
		//}
	}
}
